import com.google.inject.internal.util.$FinalizableSoftReference;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Random;


public class ConnectionManager {
    //创建数据库连接池
    private static LinkedList<Connection> pool = new LinkedList<Connection>();

    public static String Url;
    public static String USERNAME;
    public static String PASSWORD;
    public static String DRIVER;
    public static int initCount;
    public static int maxCount;
    public static int currentCount;
    public static Connection con;

    //初始化数据库连接池
    public static void initConnectionPool() throws Exception {
        for (int i = 0; i < initCount; i++) {
            pool.add(createConnection());
        }
    }

    //创建连接
    public static Connection createConnection() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        con = DriverManager.getConnection(Url, USERNAME, PASSWORD);
        return con;
    }

    //从数据库连接池中获取连接
    public static Connection getConnection() throws Exception {
        synchronized (pool) {
            if (pool.size() > 0) {
                System.out.println("当前连接数量为：" + pool.size());
                Random random = new Random();
                int i = random.nextInt(pool.size());
                return pool.get(i);
            } else if (currentCount < maxCount) {
                con = createConnection();
                pool.add(con);
                currentCount++;
                return con;
            } else {
                throw new SQLException("当前连接数量为：0");
            }
        }
    }

    /**
     * 清空连接池,释放连接
     */
    public static void clearPool() {
        for (Connection connection : pool) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        pool = new LinkedList<Connection>();
    }

    public static void release(Connection con) {
        pool.remove(con);
    }

}
